package com.platform.mvc.user;

import com.application.api.entity.ResultEntity;
import com.application.common.Api;
import com.application.common.utils.VerifyKit;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;
import com.platform.mvc.base.BaseValidator;
import com.platform.mvc.upload.UploadService;
import com.platform.tools.ToolDateTime;
import com.platform.tools.ToolRandoms;
import com.platform.tools.ToolString;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@SuppressWarnings({"unused"})
public class UserValidator extends BaseValidator {

	private static final Log log = Log.getLog(UserValidator.class);

	private UploadService uploadService;
	
	protected void validate(Controller c) {
		String actionKey = getActionKey();
		if (actionKey.equals("/platform/user/save")){
			// Upload主键和User主键共用
			String ids = ToolRandoms.getUuid(true);
			
			// 先调用getFile方法，否则无法获取参数
			List<UploadFile> files = c.getFiles("files" + File.separator + "upload", 1 * 1024 * 1024, ToolString.encoding); // 1M
			if(files != null && files.size() != 0){
				uploadService.upload("webRoot", files.get(0), ids);
			}
			
			// 传递到控制器
			c.setAttr("ids", ids);
			
			// 验证参数
			validateString("password", 6, 18, "passwordMsg", "密码不正确!");
			vali();
			
		}else if(actionKey.equals("/platform/user/update")){
			// 先调用getFile方法，否则无法获取参数
			List<UploadFile> files = c.getFiles("files" + File.separator + "upload", 1 * 1024 * 1024, ToolString.encoding); // 1M

			// 先调用getFile方法，否则无法获取参数
			if(files != null && files.size() == 1){
				UploadFile file = files.get(0);
				c.setAttr("file", file); // 传递到控制器
			}
			
			// 验证参数
			validateString("user.ids", 32, 32, "userIdsMsg", "用户主键不正确!");
			validateString("userInfo.ids", 32, 32, "userInfoIdsMsg", "用户信息主键不正确!");

			if(StrKit.notBlank(c.getPara("password"))){
				validateString("password", 6, 18, "passwordMsg", "密码不正确!");
			}
			
			vali();
		} else if(actionKey.equals(Api.user_reg) || "/admin/user/save".equals(actionKey)){
            User user = User.dao.findByUsername(c.getPara("username"));
            if (user != null) {
                addError("regMsg", "用户名已存在！");
            }
        } else if(actionKey.equalsIgnoreCase("/api/user/bind")){
			String mobile = c.getPara("mobile");
			String valicode = c.getPara("valicode");
			String openid = c.getPara("openid");

			//validateMobile("mobile", "regMsg", "手机号非空");
			validateRequired("openid", "regMsg", "openid非空");

//			if(!VerifyKit.verify(mobile, valicode)){
//				addError("regMsg", "验证码错误");
//			}
		} else if(actionKey.startsWith("/api/user/change")){
			changeVali(c, actionKey);
		}
	}

	private void changeVali(Controller c, String actionKey) {
		String mobile = c.getPara("mobile");
		String valicode = c.getPara("valicode");
		if (!VerifyKit.verify(mobile, valicode)) {
            addError("regMsg", "验证码错误");
            return;
        }

		String pay = c.getPara("password");

		if(actionKey.equalsIgnoreCase("/api/user/changePayPass")){
            if (!Pattern.matches("\\d{6}", pay)) {
                addError("regMsg", "请设置6位数字支付密码");
                return;
            }
        } else if(actionKey.equalsIgnoreCase("/api/user/changeLoginPass")){
            String tips = "密码长度6-18位,必须包含字母和数字";
            validateString("password", 6, 18, "regMsg", tips);
            validateRegex("password", "^[0-9a-zA-Z]{1,}$",  false, "regMsg", tips);
        }
	}

	protected void vali(){
		validateString("user.departmentids", 32, 32, "departmentMsg", "部门不正确!");
		validateString("user.stationids", 32, 32, "stationMsg", "岗位不正确!");

		validateString("user.idcard", 15, 18, "idcardMsg", "身份证号码不正确!");
		validateString("user.names", 2, 10, "namesMsg", "姓名不正确!");
		validateString("user.username", 5, 16, "usernameMsg", "登陆名不正确!");
		
		validateEmail("user.email", "emailMsg", "邮箱不正确!");
		validateLong("user.mobile", 10000000000L, 99999999999L, "mobileMsg", "手机号码不正确!");
		
		if(StrKit.notBlank(controller.getPara("userInfo.telephone"))){
			validateLong("userInfo.telephone", 1, 99999999999L, "telephoneMsg", "电话号码不正确!");
		}

		if(StrKit.notBlank(controller.getPara("userInfo.qq"))){
			validateLong("userInfo.qq", 1, 999999999999999L, "qqMsg", "QQ号码不正确!");
		}

		if(StrKit.notBlank(controller.getPara("userInfo.birthday"))){
			Date start = ToolDateTime.parse("1900-01-01", ToolDateTime.pattern_ymd);
			Date end = ToolDateTime.getDate();
			validateDate("userInfo.birthday", start, end, "birthdayMsg", "生日不正确!");
		}
	}
	
	protected void handleError(Controller c) {
		String actionKey = getActionKey();
		if (actionKey.equals("/platform/user/save")){
			c.keepModel(User.class);
			c.render("/platform/user/add.html");
		
		}else if (actionKey.equals("/platform/user/update")){
			c.keepModel(User.class);
			c.render("/platform/user/update.html");
		} else if(actionKey.equals(Api.user_reg) || actionKey.equals(Api.user_getvalicode)){
            c.renderJson(new ResultEntity(400, c.getAttrForStr("regMsg")));
        } else if("/admin/user/save".equals(actionKey)){
            Map<String, Object> map = new HashMap<>();
            map.put("status", 400);
            map.put("data", null);
            map.put("msg", c.getAttrForStr("regMsg"));
            map.put("url", "");
            c.renderJson(map);
        } else if(actionKey.startsWith("/api/user")){
        	c.renderJson(new ResultEntity(500, c.getAttrForStr("regMsg")));
		}
	}
	
}
